package com.hatkisoft.LockFunction.listener;

import net.rim.device.api.system.EventInjector.KeyCodeEvent;
import net.rim.device.api.system.EventInjector.KeyEvent;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.accessibility.AccessibleContext;
import net.rim.device.api.ui.accessibility.AccessibleEventListener;

public class LockScreenListener implements AccessibleEventListener{

	private static final String ACCESSIBLE_NAME_CHILD_CONTEXT = "net.rim.device.api.ui.component.TextField$AccessibleTextField";
	private static final KeyCodeEvent KEY_LOCK = new KeyCodeEvent(KeyEvent.KEY_UP , (char) Keypad.KEY_LOCK, 0);
	
	/**
	 * KeypadLock 다이얼로그가 뜨는순간 Lock키를 재빨리 다시 눌러서 다이얼로그를 없엔다  
	 */
	public void accessibleEventOccurred(int event, Object oldValue, Object newValue, AccessibleContext context) {
		if (checkLockScreen(context)) {
			KEY_LOCK.post();
		}
	}

	/** 
	 * KeypadLock을 해서 화면이 꺼졌다가 다시 켜질때 나오는 
	 * LockScreen의 각종 정보를 이용해 LockScreen인지를 판단함
	 */
	private static boolean checkLockScreen(AccessibleContext context) {
		
		if (context == null 
				|| context.getAccessibleRole() != 7
				|| context.getAccessibleStateSet() != 8
				|| context.getAccessibleChildCount() != 1)
			return false;
		
		AccessibleContext chileContext = context.getAccessibleChildAt(0);
		if (chileContext == null 
				|| chileContext.getAccessibleRole() != 2 
				|| chileContext.getAccessibleChildCount() != 0 
				|| chileContext.getAccessibleName().equals(ACCESSIBLE_NAME_CHILD_CONTEXT))
			return false;
		
		return true;
	}
}
